const path = require('path');
const express = require('express');
const logger = require('morgan');
const nunjucks = require('nunjucks');
const session = require('express-session');

// 导入路由
const userRouter = require('./routes/user.js');
const counterRouter = require('./routes/counter.js');

const port = 3000;
const app = express();

// 设置 模板文件 根路径
const templateRoot = path.resolve(__dirname, 'views');
const suffix = 'njk' ; // 指定模板文件名称后缀
app.set('views', templateRoot);
app.set('view engine' , suffix );

// 配置 nunjucks 引擎
nunjucks.configure( templateRoot , {
    autoescape: true ,
    express: app
});

app.use(logger('dev'));
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.urlencoded({ extended: false }));
app.use(express.json());

// 调用 session 函数返回一个用来处理会话的中间件
const sessionMiddleware = session({ 
    // 设置在客户端保存的与会话对应的cookie名称
    name: 'SESSIONID',
    secret:'ecut', 
    resave: false, 
    saveUninitialized: true, 
    // 在客户端保存的与会话对应的cookie的相关配置
    cookie:{
        path: '/' ,
        secure: false,
        httpOnly: true,
    } 
});
// 启用 session 中间件支持
app.use( sessionMiddleware );

// 启用路由
app.use( userRouter );
app.use( counterRouter );

app.listen(port, ()=> console.log(`正在监听${port}端口`) );